package com.huqs.smoothphotoview.library.ui;
import android.Manifest;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.apkfuns.logutils.LogUtils;
import com.huqs.smoothphotoview.library.download.DownLoadImageService;
import com.huqs.smoothphotoview.library.download.ImageDownLoadCallBack;
import com.huqs.smoothphotoview.library.fragment.PhotoFragment;
import com.huqs.smoothphotoview.library.view.SmoothImageView;
import com.huqs.smoothphotoviewer.library.R;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import java.util.ArrayList;
import java.util.List;

public class PhotoActivity extends FragmentActivity implements ViewTreeObserver.OnGlobalLayoutListener, View.OnClickListener {
    private static final int WRITE_EXTERNAL_STORAGE = 100;
    private ViewPager mViewPager;
    private String imgUrls[];
    private ArrayList<Rect> rects;
    private ArrayList<PhotoFragment> fragments;
    private int index;
    private PhotoFragmentAdapter adapter;
    public View mRootView;
    private TextView mTextPageCount;
    private ImageView mBtnDownload;
    private int mPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_photo);
        mRootView = findViewById(R.id.root);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mTextPageCount = (TextView) findViewById(R.id.tv_page_count);
        mBtnDownload = (ImageView) findViewById(R.id.btn_image_download);
        mBtnDownload.setOnClickListener(this);
        imgUrls = getIntent().getStringArrayExtra("imgUrls");
        rects = getIntent().getParcelableArrayListExtra("bounds");
        index = getIntent().getIntExtra("index", 0);
        mPosition = index;
        if (rects == null || imgUrls == null) {
            finish();
        } else {
            int position = index + 1;
            mTextPageCount.setText(String.format("%d/%d", position, imgUrls.length));
            adapter = new PhotoFragmentAdapter(getSupportFragmentManager());
            fragments = new ArrayList<>();
            int rectSize = rects.size();
            for (int i = 0; i < imgUrls.length; i++) {
                PhotoFragment fragment = new PhotoFragment();
                Bundle bundle = new Bundle();
                bundle.putString("img", imgUrls[i]);
                if (i < rectSize) {
                    bundle.putParcelable("startBounds", rects.get(i));
                }
                fragment.setArguments(bundle);
                fragments.add(fragment);
            }
            mViewPager.setTag(false);
            mViewPager.setAdapter(adapter);
            mViewPager.getViewTreeObserver().addOnGlobalLayoutListener(this);
            mViewPager.setCurrentItem(index);
            mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    mPosition = position;
                    mTextPageCount.setText(String.format("%d/%d", ++position, imgUrls.length));
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

        }
        //设置背景渐变，如果图片没有缓存的情况下就会显现背景透明的情况
        ValueAnimator colorAnim = ObjectAnimator.ofInt(mRootView,"backgroundColor", Color.TRANSPARENT, Color.BLACK);
        colorAnim.setDuration(300);
        colorAnim.setEvaluator(new ArgbEvaluator());
        //colorAnim.setRepeatCount(ValueAnimator.INFINITE);
        colorAnim.setRepeatMode(ValueAnimator.REVERSE);
        colorAnim.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 只需要调用这一句，第一个参数是当前Acitivity/Fragment，回调方法写在当前Activity/Framgent。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 成功回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionYes(WRITE_EXTERNAL_STORAGE)
    private void getLocationYes(List<String> grantedPermissions) {
        downLoad(imgUrls[mPosition]);
    }

    // 失败回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionNo(WRITE_EXTERNAL_STORAGE)
    private void getLocationNo(List<String> deniedPermissions) {
        LogUtils.d(deniedPermissions);
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, WRITE_EXTERNAL_STORAGE).show();
        }
    }

    String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    @Override
    public void onClick(View view) {
        // 先判断是否有权限。
        if (AndPermission.hasPermission(this, perms)) {
            // 有权限，直接do anything.
            downLoad(imgUrls[mPosition]);
        } else {
            // 申请权限。
            AndPermission.with(this).requestCode(100).permission(perms).send();
        }
    }

    @Override
    public void onGlobalLayout() {
        PhotoFragment fragment = fragments.get(index);
        fragment.transformIn(new SmoothImageView.onTransformListener() {
            @Override
            public void onTransformCompleted(SmoothImageView.Status status) {
                //mRootView.setBackgroundColor(Color.BLACK);
                mTextPageCount.setVisibility(View.VISIBLE);
                mBtnDownload.setVisibility(View.VISIBLE);
            }
        });
        mViewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }
    private class PhotoFragmentAdapter extends FragmentPagerAdapter {
        public PhotoFragmentAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            PhotoFragment fragment = fragments.get(position);
            return fragment;
        }
        @Override
        public int getCount() {
            return fragments == null ? 0 : fragments.size();
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mTextPageCount.setVisibility(View.GONE);
                transformOut();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    public void transformOut() {
        if ((boolean) mViewPager.getTag()) return;
        mTextPageCount.setVisibility(View.GONE);
        mBtnDownload.setVisibility(View.GONE);
        mRootView.setBackgroundColor(Color.TRANSPARENT);
        int currentIndex = mViewPager.getCurrentItem();
        mViewPager.setTag(true);
        if (currentIndex < rects.size()) {
            PhotoFragment fragment = fragments.get(currentIndex);
            fragment.transformOut(new SmoothImageView.onTransformListener() {
                @Override
                public void onTransformCompleted(SmoothImageView.Status status) {
                    finish();
                    PhotoActivity.this.overridePendingTransition(0, 0);
                }
            });
        } else {
            finish();
            this.overridePendingTransition(0, 0);
        }
    }
    /**
     * 启动图片下载线程
     */
    private void downLoad(String url) {
        DownLoadImageService service = new DownLoadImageService(this,
                url,
                new ImageDownLoadCallBack() {
                    @Override
                    public void onStart() {
                        Toast.makeText(PhotoActivity.this, "正在保存图片", Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onDownLoadSuccess() {
                        Toast.makeText(PhotoActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onFileExists() {
                        Toast.makeText(PhotoActivity.this, "图片已存在", Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onDownLoadFailed() {
                        Toast.makeText(PhotoActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                    }
                });
        //启动图片下载线程
        new Thread(service).start();
    }
}
